//文件上传
jQuery(function() {
    var $ = jQuery,
        $list = $('#thelist'),
        $btn = $('#ctlBtn'),
        state = 'pending',
        uploader;
    var jsonData = {
            fileList: []
        };

    uploader = WebUploader.create({
    	auto: true,
        // swf文件路径
        swf:'Uploader.swf',
        // 文件接收服务端。
        server:'/webupload/uploadFile',
        // 不压缩image
        resize: false, 
         // 内部根据当前运行是创建，可能是input元素，也可能是flash.
         pick: '#picker' ,
         timeout: 0,
         chunked: true, 
         chunkSize: 1024*1024*50, 
         threads: 1, 
         fileNumLimit: 1, 
         fileSingleSizeLimit: 5000* 1024 * 1024, 
         duplicate: true
        
    });

    function isIE_Test() { //ie?
        if (!!window.ActiveXObject || "ActiveXObject" in window)
            return true;
        else
            return false;
    }

    function containSpecial(strForText )
    {
        var str = "[@/'\"#$%&^*]+";
        var reg = new RegExp(str);
        if(reg.test(strForText))
        {
          return true;
        } else{
            return false;
        }
    }

    // 当有文件添加进来的时候
    uploader.on( 'fileQueued', function( file ) {
        var fileName = file.name;
        var ieFlag = isIE_Test();
       // alert("ieFlag--"+ieFlag);

        if(!ieFlag){
            var spFlag = containSpecial(fileName);
            //alert("spFlag--"+spFlag);

            if(spFlag){
                alert("文件名称有特殊字符,请重新修改下");
            }
        }

        $list.append( '<div id="' + file.id + '" class="item">' +
            '<h4 class="info">' + file.name + '</h4>' +
            '<p class="state" style="display:inline-block">等待上传...</p>' +
        '</div>' );
    });

    // 文件上传过程中创建进度条实时显示。
    uploader.on( 'uploadProgress', function( file, percentage ) {
        var $li = $( '#'+file.id ),
            $percent = $li.find('.progress .progress-bar');
        // 避免重复创建
        if ( !$percent.length ) {
            $percent = $('<div class="progress progress-striped active">' +
              '<div class="progress-bar" role="progressbar" style="width: 0%">' +
              '</div>' +
            '</div>').appendTo( $li).find('.progress-bar');
        }
        $li.find('p.state').text('上传中  '+ parseInt(percentage * 100) + '%');
        $percent.css( 'width', parseInt(percentage * 100 )+ '%' );
    });

    $list.on( 'click', '.del', function() {
    	var $ele = $(this);
    	
    	var id = $ele.parent().attr("id");
    	var name = uploader.getFile(id).name;
    	//删除页面div
    	$("#"+id).html("");
    	
    	//删除本地文件
    	$.each(jsonData.fileList, function (index, item) {
            if (item && item.fileName === name) {
            	//更改隐藏输入框值
            	var JName = $("#fileName").val();
            	var JDocUrl = $("#docUrl").val();
            	
            	var ArrayName = new Array(); //定义一数组名称
            	ArrayName = JName.split(","); //字符分割 

            	var ArrayDocUrl = new Array(); //定义一数组路径
            	ArrayDocUrl = JDocUrl.split(","); //字符分割
            	
            	var Sname = "";//删除后的名称字符串
            	var SDocURl = "";//删除后的路径字符串
            	for(var i=0;i<ArrayName.length ;i++){
            		if(ArrayName[i] != item.fileName && ArrayName[i].length>0){
            			Sname += ArrayName[i]+",";
            		}
            	}
            	for(var i=0;i<ArrayDocUrl.length ;i++){
            		if(ArrayDocUrl[i] != item.docUrl &&ArrayDocUrl[i].length>0){
            			SDocURl += ArrayDocUrl[i]+",";
            		}
            	}
            	$("#fileName").val(Sname.slice(0,Sname.length-1));//名称重新赋值
            	$("#docUrl").val(SDocURl.slice(0,SDocURl.length-1));//路径重新赋值
            	
            	//本地删除
            	$.post("/webupload/delete",{docUrl:item.docUrl},function(result){
            	});
            }
        });
    	
    	
    });
    uploader.on( 'uploadSuccess', function( file,response ) {
        $( '#'+file.id ).find('p.state').text('已上传');
        var str = $( '#'+file.id ).find('.info').text();//文件名
        $( '#'+file.id ).find('.info').text(str);
        $( '#'+file.id ).append("<a class='del' style='display:inline-block;margin-left:55px;'>删除</a>");
        
        var fileName = $("#fileName").val();
        if(fileName.length>0){
        	$("#fileName").val(fileName + "," + response.fileName);
            $("#docUrl").val($("#docUrl").val() + "," + response.docUrl);
            
        }else{
        	$("#fileName").val(response.fileName);
        	alert(response.fileName+"   "+response.docUrl)
        	$("#docUrl").val(response.docUrl);
        }
        var fileEvent = {
            fileName: response.fileName,
            docUrl: response.docUrl
        };
        jsonData.fileList.push(fileEvent);
        
    });

    uploader.on( 'uploadError', function( file,reason ) {
        $( '#'+file.id ).find('p.state').text('上传出错'+reason);
    });

    uploader.on( 'uploadComplete', function( file ) {
        $( '#'+file.id ).find('.progress').fadeOut();
    });

    uploader.on( 'all', function( type ) {
        if ( type === 'startUpload' ) {
            state = 'uploading';
        } else if ( type === 'stopUpload' ) {
            state = 'paused';
        } else if ( type === 'uploadFinished' ) {
            state = 'done';
        }

        if ( state === 'uploading' ) {
            $btn.text('暂停上传');
        } else {
            $btn.text('开始上传');
        }
    });

    /* $btn.on( 'click', function() {
        if ( state === 'uploading' ) {
            uploader.stop();
        } else {
            uploader.upload();
        }
    }); */
});